<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Jobs\SearchJob;
use App\Models\FakeUser;
use App\Models\Star;
use App\Models\User;
use App\Models\UserJoinCircle;
use App\Services\User\FocusRecService;
use App\Services\User\GetStareCountService;
use App\Services\User\GetStaredCountService;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;


class UserController extends BaseController
{

    public function index(Request $request) {
        $input = $request->input();
        $nickname = $input['title'] ?? '';
        $my_user_id = $this->getUserId();
        $action = $request->input('action');
        $from = $request->input('from');
        $circle_id = $request->input('circle_id');
        $order_by_key = $request->input('order_by_key', 'users.id');
        $order_by_value = $request->input('order_by_value', 'desc');

        if ($action == 'circle_users') {
            $list = $this->_searchCircleUser($circle_id);
        } else {
            if($action == 'hot_search') {
                $list = new User();
                $order_by_key = 'hot_search_weight';
            } else if($action == 'focus') {
                $order_by_key = 'focus.created_at';
                $cur_user_id = $request->input('user_id') ?: $my_user_id;
                $list = User::join('focus', function ($join) use($cur_user_id){
                    $join->on('users.id', 'focus.target_user_id');
                })->where('user_id', $cur_user_id);
            } else if($action == 'fans') {
                $order_by_key = 'focus.created_at';
                $cur_user_id = $request->input('user_id') ?: $my_user_id;
                $list = User::join('focus', function ($join) use($cur_user_id){
                    $join->on('users.id', 'focus.user_id')->where('focus.target_user_id', $cur_user_id);
                });
            } else if($action == 'search') {
                $list = User::when($nickname, function ($q) use($nickname) {
                    $q->where('nickname', 'like', '%' . $nickname . '%');
                });
                $this->dispatch(new SearchJob($my_user_id, $nickname));
            } else if($action == 'rec_focus') {
                $list = new User();
                $arr_id = FocusRecService::handle();
                $list = $list->whereIn('id', $arr_id);
            } else {
                $list = new User();
            }
            $list = $list->where('is_black', 0)->select('users.id','users.nickname','users.avatar_url')
                ->withCertain('animal', ['user_id','title', 'birthday', 'category_title', 'birthday'])
                ->withCount(['is_focus' => function($qr) use($my_user_id){
                    $qr->where('user_id', $my_user_id);
                }])
                ->orderBy($order_by_key, $order_by_value)->paginate(per_page());
        }
        if ($from == 'notify' && $my_user_id) {
            Redis::del('user_latest_fans_count_' . $my_user_id);
        }
        return $this->paginate($list);
    }

    public function _searchCircleUser($circle_id) {
        $id = $circle_id;
        $user_id = $this->getUserId();
        $list = UserJoinCircle::join('users', 'users.id', 'user_join_circles.user_id')
            ->where('circle_id', $id)
            ->select('users.nickname', 'user_id', 'users.avatar_url','user_join_circles.is_owner')
            ->withCertain('animal', ['user_id','title', 'category_title', 'birthday'])
            ->withCount(['is_focus' => function($qr) use($user_id){
                $qr->where('user_id', $user_id);
            }])
            ->orderBy('is_owner', 'desc')
            ->orderBy('users.id', 'desc')
            ->paginate(per_page());
        return $list;
    }

    public function fake_uid() {
        $uid = app('snowflake')->id();
        FakeUser::create([
            'user_id' => $uid,
            'ip' => get_client_ip(),
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        return $this->success(['uid' => $uid]);
    }

    public function info(Request $request)
    {
        $user_id = $this->getUserId();
        $id = $request->input('id', $user_id);
        if (!$id)
            abort(401);
        $info = User::withCount(['is_focus' => function ($qr) use ($user_id) {
            $qr->where('user_id', $user_id);
        }])->find($id);
        if (!$info)
            return $this->failed('用户不存在');
        $info->stared_count = GetStaredCountService::handle($id);
        $info->star_count = GetStareCountService::handle($id, Star::TYPE_ARTICLE);
        return $this->success($info);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'nickname' => 'filled'
        ]);
        $input = $request->input();
        $user = $this->getUser();
        $user->update($input);
        return $this->success(['id' => $user->id]);
    }
}

